package com.daiyang.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.daiyang.blog.pojo.AddBlogInfoParam;
import com.daiyang.blog.service.DTO.BlogInfoResponse;
import com.daiyang.blog.mapper.BlogInfoMapper;
import com.daiyang.blog.pojo.BlogInfo;
import com.daiyang.blog.service.BlogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BlogServiceImpl implements BlogService {
    @Resource(name= "blogInfoMapper")
    private BlogInfoMapper blogInfoMapper;

    public List<BlogInfoResponse> getList() {
        List<BlogInfo> blogInfos = blogInfoMapper.selectList(new LambdaQueryWrapper<BlogInfo>()
                .eq(BlogInfo::getDeleteFlag,0).orderByDesc(BlogInfo::getId));


        List<BlogInfoResponse> blogInfoResponses = blogInfos.stream().map(blogInfo -> {
            BlogInfoResponse blogInfoResponse = new BlogInfoResponse();
            BeanUtils.copyProperties(blogInfo, blogInfoResponse);
            return blogInfoResponse;
        }).collect(Collectors.toList());
        return blogInfoResponses;
    }

    public BlogInfoResponse getBlogDetail(Integer blogId) {
        BlogInfo blogInfo = blogInfoMapper.selectById(blogId);
        log.info("getBlogDetail blogId:{}", blogId);
        log.info("getBlogDetail blogInfo:{}", blogInfo);
        BlogInfoResponse blogInfoResponse = new BlogInfoResponse();
        BeanUtils.copyProperties(blogInfo, blogInfoResponse);
        return blogInfoResponse;
    }

    @Override
    public Boolean addBlog(AddBlogInfoParam addBlogInfoParam) {
        BlogInfo blogInfo = new BlogInfo();
        BeanUtils.copyProperties(addBlogInfoParam, blogInfo);
        Integer result = null;
        try {
            result = insertBlog(blogInfo);
            if (result==1){
                return true;
            }
        }catch (Exception e){
            log.error("发布博客失败, e:", e);
        }
        return false;
    }
    private Integer insertBlog(BlogInfo blogInfo) {
        return blogInfoMapper.insert(blogInfo);
    }
}
